package club.babyf.nativeai.demo.algorithm;

/**
 * ReverseList.
 *
 * @author zhanglei.
 * @date 2025/4/12 11:14.
 * @description 反转链表.
 */
public class _5_ReverseList {

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode current = head;
        while (current != null) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(head);
        _5_ReverseList reverseList = new _5_ReverseList();
        ListNode reversedList = reverseList.reverseList(head);
        System.out.println(reversedList);
    }

    public static class ListNode {

        int value;

        ListNode next;

        ListNode() {

        }

        ListNode(int value) {
            this.value = value;
        }

        ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.value);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

}
